<template>
	<view class="y-flex y-flex-1">
		<module-list
		ref="list"
		:component="components"
		:cell="cell"
		:comment="comments"
		:bounce="pageStyle.enableBounce"
		:back-top-show="pageStyle.enableBackTop"
		:refreshImage="pageStyle.pulldownRefreshImage"
		:pulldownable="pageStyle.enablePulldown == 1"
		:loadmoreable="pageStyle.enableLoadmore == 1"
		:loadingColor="pageStyle.loadingColor"
		:backTopImage="pageStyle.backTopImage"
		:params="detail"
		@scroll="handleScroll"
		@pulldown="handlePulldown"
		@loaded="handleModuleLoaded">
			<template #top v-if="detail && detail.title">
				<cell v-if="detail && detail.title">
					<find-detail ref="detail"
					:data="detail"
					:options="detailOptions"
					:bg-color="componentStyle['background-color']"
					:style="componentStyle"
					@utils="handleUtils"
					@startClick="handleStartClick"
					@continueClick="handleContinueClick"></find-detail>
				</cell>
			</template>
		</module-list>
	</view>
</template>

<script>
	import ModuleList from '../components/ModuleList.vue'
	import FindDetail from '../components/FindModule/FindDetail.vue'
	import { openDB, closeDB, insert, update } from '@/assets/database'
	import { pixelunit, isContained, hexToRgba } from '@/assets/js/util.js'
	export default {
		inject: ['getSkinColor', 'getPage', 'getComponentStyle', 'getPageStyle', 'getQuery', 'confirm', 'toast'],
		components: {
			ModuleList,
			FindDetail
		},
		computed: {
			$Router () {
				return getApp().globalData.$Router
			},
			history () {
				return this.$store.getters['setting/GET_HISTORY']
			},
			skinColor () {
				return this.getSkinColor()
			},
			//路由参数
			query () {
				return this.getQuery()
			},
			page () {
				return this.getPage()
			},
			pageStyle () {
				return this.getPageStyle()
			},
			components () {
				return this.page?.components || []
			},
			cell () {
				return this.page?.cell || {}
			},
			comments () {
				return this.page?.comments || {}
			},
			componentStyle () {
				const style = this.getComponentStyle()
				return {
					'margin-top': pixelunit(style.marginTop),
					'margin-bottom': pixelunit(style.marginBottom),
					'margin-left': pixelunit(style.marginLeft),
					'margin-right': pixelunit(style.marginRight),
					'background-color': hexToRgba(style.backgroundColor, style.backgroundOpacity),
					'border-radius': pixelunit(style.borderRadius)
				}
			},
			detailOptions () {
				return {
					startText: '查看更多',
					continueText: '继续观看',
					recordText: '观看记录',
					enableButton: this.page?.items ? 1 : 0
				}
			},
			network () {
				return this.$store.getters['network/GET']
			},
			pixelunit () {
				return pixelunit
			}
		},
		data () {
			return {
				detail: {}
			}
		},
		mounted () {
			this.$nextTick(this.handlePulldown)
		},
		methods: {
			onShow () {
				this.$refs.detail && this.$refs.detail.getRecord()
			},
			onBackPress () {
				if ( this.detail.uniqueId ) {
					if ( this.history == 0 && !this.page?.items ) {
						this.confirm({
							title: '记录提示',
							content: '是否记录当前看的文章？',
							cancelText: '取消记录',
							confirmText: '保存记录',
							success: res => {
								if ( res.confirm ) {
									this.saveRecord()
								} else {
									uni.navigateBack()
								}
							}
						})
					} else if ( this.history == 1 ) this.saveRecord()
					else uni.navigateBack()
					return true
				}
				return false
			},
			async saveRecord () {
				await openDB()
				try{
					const record = this.$refs.detail.record
					if ( record.id ) {
						await update('record', {
							url: this.detail.url,
							title: this.detail.title || '',
							cover: this.detail.cover || '',
							is_adult: this.detail.isAdult,
							source_id: this.detail.sourceId
						}, 'id = ' + record.id)
					} else {
						await insert('record', {
							unique_id: this.detail.uniqueId,
							url: this.detail.url,
							title: this.detail.title || '',
							cover: this.detail.cover || '',
							is_adult: this.detail.isAdult,
							source_id: this.detail.sourceId
						})
					}
					closeDB()
					uni.navigateBack()
				}catch(e){
					closeDB()
					this.toast(e.message)
					setTimeout(() => {
						uni.navigateBack()
					}, 500)
				}
			},
			handleUtils (e) {
				this.$emit('utils', e)
			},
			handleStartClick () {
				this.readMore()
			},
			handleContinueClick (record) {
				this.readMore(record.current)
			},
			handleScroll (e) {
				this.$emit('scroll', Math.abs(e.contentOffset.y))
			},
			readMore (current = 1) {
				this.$Router.push({
					path: '/pages/find/article/reader',
					query: {
						items: this.page?.items || {},
						detail: this.detail,
						query: this.query,
						current
					}
				})
			},
			handleModuleLoaded () {
				this.$emit('loaded', true)
				this.$refs.list && this.$refs.list.pulldownSuccess()
			},
			async handlePulldown (callback) {
				try{
					this.detail = await this.handleGetDetail()
					this.$nextTick(function () {
						this.$refs.detail && this.$refs.detail.getRecord()
						this.$refs.list && this.$refs.list.initModule(callback, true)
					})
				}catch(e){
					this.$emit('loaded', true)
				}
			},
			async handleGetDetail () {
				const detail = this.page?.detail || {}
				const staticData = await this.network.staticDataHandle(detail.staticData || {}, this.query)
				const dynamicData = detail.dynamicData
				const request = detail.request
				let data = {}
				if ( dynamicData && request ) {
					const newRequest = await this.network.requestHandle(request, this.query)
					const response = await this.network.$request(newRequest)
					data = await this.network.$list(dynamicData, response.data, response.taskId)
					data.uniqueId = data.id || this.network.getUniqueId(newRequest)
					if ( !data.shareUrl && !staticData.shareUrl ) data.shareUrl = await this.network.getShareUrl(newRequest)
				}
				return Object.assign({}, staticData, data)
			}
		}
	}
</script>

<style>
</style>